package dht.server;

import dht.IDataServerRouteTable;
import dht.IRoutineHandler;
import dht.IServer;
import dht.entity.GlobalVariables;
import dht.entity.Message;
import dht.entity.MessageType;
import dht.throwable.DhtException;
import dht.util.IdGenerator;

public class DataServerRoutineHandlerImpl implements IRoutineHandler {

	protected int tableUpdatePeriod;
	protected IServer server;
	protected IDataServerRouteTable routeTable;

	public DataServerRoutineHandlerImpl(IServer server,
			IDataServerRouteTable routeTable) {
		this.tableUpdatePeriod = GlobalVariables.tableUpdatePeriod;
		this.server = server;
		this.routeTable = routeTable;
	}

	@Override
	public void run() {
		Message msg = null;
		msg = new Message(IdGenerator.genTransactionId(), MessageType.JOIN_REQ,
				server.getLocalInfo());
		msg.setSenderNodeInfo(server.getLocalInfo());
		try {
			server.handleInitiativeTransaction(routeTable.getMasterInfo(), msg,
					true);
		} catch (DhtException e) {
			e.printStackTrace();
			return;
		}
		while (true) {
			try {
				Thread.sleep(tableUpdatePeriod);
			} catch (InterruptedException e) {
				e.printStackTrace();
				continue;
			}
			msg = new Message(IdGenerator.genTransactionId(),
					MessageType.SERVER_TABLE_REQ, server.getLocalInfo());
			try {
				server.handleInitiativeTransaction(routeTable.getMasterInfo(),
						msg, true);
			} catch (DhtException e) {
				e.printStackTrace();
				continue;
			}
		}
	}
}
